package com.sgmw.iamgeqr_flutter_plugin

import android.annotation.TargetApi
import androidx.annotation.NonNull
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import com.sgmw.iamgeqr_flutter_plugin.ImageActivity

/** IamgeqrFlutterPlugin */
class IamgeqrFlutterPlugin2: FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private lateinit var channel : MethodChannel
  private lateinit var context : Context
  private lateinit var _result : Result
  private lateinit var myBroadcastReceiver: MyBroadcastReceiver

  @TargetApi(Build.VERSION_CODES.O)
  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "iamgeqr_flutter_plugin")
    channel.setMethodCallHandler(this)
    context = flutterPluginBinding.applicationContext

    myBroadcastReceiver = MyBroadcastReceiver()

    // 创建 IntentFilter 并注册广播接收器
    val intentFilter = IntentFilter().apply {
      addAction("com.sgmw.flutter.imageQr")
    }
    //registerReceiver(myBroadcastReceiver, intentFilter)
    context.registerReceiver(myBroadcastReceiver, intentFilter, Context.RECEIVER_EXPORTED);
  }

  override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
    if (call.method == "getPlatformVersion") {
      result.success("Android ${android.os.Build.VERSION.RELEASE}")
    }else if(call.method == "imageScanQr"){
      myBroadcastReceiver.setResult(result)
      val intent = Intent(context, ImageActivity::class.java)
      intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
      context.startActivity(intent)
    } else {
      result.notImplemented()
    }
  }

  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
    context.unregisterReceiver(myBroadcastReceiver)
  }

  class MyBroadcastReceiver : BroadcastReceiver() {
    private lateinit var _result: Result

    fun setResult(result : Result){
      this._result = result
    }

    override fun onReceive(context: Context, intent: Intent) {
      val action = intent.action
      when (action) {
        "com.sgmw.flutter.imageQr" -> {
          if (::_result.isInitialized) {
            _result.success(intent.getStringExtra("QRTEXT"))
          }
        }
      }
    }
  }
}